﻿using Assets.Scripts.UI;
using System.Collections;
using UnityEngine;

namespace SuperScrollView
{

    public class SuperListView : MonoBehaviour
    {
        protected SuperListViewItem.OnSelectDelegate OnSelctItem = null;
        protected SuperListViewItem.OnShowDelegate OnShowItem = null;

        public LoopListView2 mLoopListView;
        public string mItemPrefabName = "ItemPrefab";

        public int mDataCount = 0;

        public void Init(SuperListViewItem.OnSelectDelegate selctItemFunc, SuperListViewItem.OnShowDelegate showItemFunc)
        {
            int totalCount = -1;
            OnSelctItem = selctItemFunc;
            OnShowItem = showItemFunc;
            mLoopListView.InitListView(totalCount, OnGetItemByIndex);
        }
        public void SetItemPrefabName(string prefabName)
        {
            mItemPrefabName = prefabName;
        }
        virtual public LoopListViewItem2 OnGetItemByIndex(LoopListView2 listView, int index)
        {
            if (index < 0 || index >= listView.ItemTotalCount)
            {
                return null;
            }
            LoopListViewItem2 item = listView.NewListViewItem(mItemPrefabName);
            item.gameObject.name = "Item_" + index;
            SuperListViewItem itemScript = item.GetComponent<SuperListViewItem>();
            if (item.IsInitHandlerCalled == false)
            {
                item.IsInitHandlerCalled = true;
                itemScript.Init();
                itemScript.OnSelectItem = OnSelctItem;
                itemScript.OnShowItem = OnShowItem;
            }
            itemScript.SetItemData(index);
            return item;
        }

        virtual public void SetCount(int count, bool resetPos = false, int moveIndex = -1)
        {
            mDataCount = count;
            if (mLoopListView.ItemTotalCount == count)
                RefreshList();
            else
            {
                mLoopListView.SetListItemCount(mDataCount, resetPos, moveIndex);
            }
        }
        public void RefreshList()
        {
            mLoopListView.RefreshAllShownItem();
        }

        public void MovePanelToItemIndex(int index, float offset = 0)
        {
            mLoopListView.MovePanelToItemIndex(index, offset);
        }

        public void ContentSize()
        {
            StartCoroutine(DoContentSize());
        }

        public IEnumerator DoContentSize()
        {
            yield return new WaitForSeconds(0);
            var contents = GetComponentsInChildren<CustomSize>();

            foreach (var child in contents)
            {
                if (child.gameObject.activeInHierarchy)
                    child.RefreshContentSize();
            }
        }

    }
}



